<template>
  <div class="app-container">
    <!-- 搜索筛选操作栏 -->
    <div class="filter-container clearfix">
      <el-button v-waves class="filter-item" @click="handleCreate">
        添加文章
      </el-button>
    </div>

    <!-- 表格 -->
    <el-table
      :key="tableKey"
      ref="table"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%"
    >
      <el-table-column align="center" label="文章标题" prop="title" />
      <el-table-column align="center" label="发布时间" prop="created_at" />
      <el-table-column align="center" label="操作">
        <template slot-scope="{ row }">
          <el-button
            size="mini"
            plain
            type="primary"
            @click="handleUpdate(row)"
          >
            编辑
          </el-button>
          <el-button
            size="mini"
            plain
            type="danger"
            @click="handleDelete(row.id)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div v-if="total > 0" style="text-align: right">
      <pagination
        :total="total"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.per_page"
        @pagination="getList"
      />
    </div>

    <!-- 添加&编辑 -->
    <el-dialog
      :title="type == 0 ? '添加文章' : '编辑文章'"
      :visible.sync="dialogVisible"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      destroy-on-close
      width="900px"
      @closed="dialogClosed"
    >
      <el-form
        ref="postForm"
        :model="form"
        :rules="rules"
        class="form-container"
      >
        <div class="createPost-main-container">
          <el-form-item label-width="120px" label="文章标题:" prop="title">
            <el-input v-model.trim="form.title" />
          </el-form-item>
          <el-form-item label-width="120px" label="上传图片:" prop="image_url">
            <el-upload
              :file-list="fileList"
              action="#"
              :limit="1"
              accept=".jpg,.jpeg,.png,.JPG,.JPEG"
              list-type="picture-card"
              :http-request="
                (file) => {
                  return uploadImgHandle(file);
                }
              "
              :on-remove="
                (file, fileList) => {
                  return removeHandle(file, fileList);
                }
              "
              :class="{ hide: fileList.length > 0 }"
            >
              <i class="el-icon-plus" />
            </el-upload>
          </el-form-item>
          <el-form-item label-width="120px" label="内容:" prop="content">
            <Tinymce
              v-if="type == 0 || form.content"
              ref="editor"
              v-model="form.content"
              :height="400"
            />
          </el-form-item>
        </div>
      </el-form>
      <div style="margin-top: 40px; text-align: center">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="danger" @click="handleToggleEdit">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getArticleList,
  createArticle,
  updateArticle,
  deleteArticle,
  uploadFile
} from '@/api/common'
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import Tinymce from '@/components/Tinymce'

export default {
  name: 'ArticleList',
  components: {
    Pagination,
    Tinymce
  },
  directives: {
    waves
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      dialogVisible: false,
      type: 0,
      fileList: [],
      listQuery: {
        page: 1,
        per_page: 20
      },
      form: {
        content: undefined,
        title: undefined,
        image_url: undefined
      },
      rules: {
        title: [
          {
            required: true,
            message: '请输入文章标题',
            trigger: 'blur'
          }
        ],
        image_url: [
          {
            required: true,
            message: '请上传图片',
            trigger: 'change'
          }
        ],
        content: [
          {
            required: true,
            message: '请输入文章内容',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    removeHandle() {
      this.fileList = []
    },
    uploadImgHandle(e) {
      const formData = new FormData()
      formData.append('file', e.file)
      uploadFile(formData).then((res) => {
        this.fileList = [
          {
            url: this.$store.state.settings.imgHost + res.data
          }
        ]
        this.form.image_url = res.data
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    getList() {
      this.listLoading = true
      getArticleList(this.listQuery)
        .then((response) => {
          const { data, total } = response.data
          this.list = data
          this.total = total
        })
        .finally(() => {
          this.listLoading = false
        })
    },
    // 编辑
    handleUpdate(row) {
      this.type = 1
      this.form = Object.assign({}, row)
      this.fileList = [
        {
          url: this.$store.state.settings.imgHost + row.image_url
        }
      ]
      this.dialogVisible = true
    },
    // 新增
    handleCreate() {
      this.type = 0
      this.dialogVisible = true
    },
    // 处理新增||处理编辑
    handleToggleEdit() {
      this.$refs.postForm.validate(async(valid) => {
        if (valid) {
          this.listLoading = true
          if (this.type == 0) {
            createArticle(this.form)
              .then(() => {
                this.$notify({
                  title: '提示',
                  message: '新增成功',
                  type: 'success',
                  duration: 2000
                })
                this.dialogVisible = false
                this.getList()
              })
              .catch(() => {
                this.listLoading = false
              })
          } else {
            updateArticle(this.form['id'], this.form)
              .then(() => {
                this.$notify({
                  title: '提示',
                  message: '编辑成功',
                  type: 'success',
                  duration: 2000
                })
                this.dialogVisible = false
                this.getList()
              })
              .catch(() => {
                this.listLoading = false
              })
          }
        }
      })
    },
    dialogClosed() {
      this.form = {
        title: undefined,
        content: undefined,
        image_url: undefined
      }
      this.fileList = []
      this.$refs['postForm'].resetFields()
    },
    // 删除
    handleDelete(id) {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.listLoading = true
          deleteArticle(id)
            .then(() => {
              // 用于判断删除最后一页的所有数据，自动减少一页数据
              if (
                this.list.length == 1 &&
                this.listQuery.page > 1 &&
                this.listQuery.page >
                  parseInt((this.total - 1) / this.listQuery.per_page)
              ) {
                this.listQuery.page = this.listQuery.page - 1
              }
              this.$notify({
                title: '提示',
                message: '删除成功',
                type: 'success',
                duration: 2000
              })
              this.getList()
            })
            .catch(() => {
              this.listLoading = false
            })
        })
        .catch(() => {})
    }
  }
}
</script>

<style>
.el-upload-list__item.is-ready,
.el-upload-list__item.is-uploading {
  display: none !important;
}

.hide .el-upload--picture-card {
  display: none;
}

.el-upload-list__item {
  transition: none !important;
}
</style>
